<template>
  <!-- 页面-单据序列管理-添加 -->
  <div class="run-modal-style">
    <Form
      :model="modelForm"
      ref="editForm"
      class="ivu-form-no-margin-bottom"
      :rules="rule"
      :label-width="110"
    >
      <Row :gutter="32" class="code-row-bg">
        <Col span="12" style="border:none;">
          <Form-item prop="receiptSeqCode" :label="$t('module.receiptSequence.receiptSeqCode')">
            <Input
              :placeholder="$t('module.receiptSequence.enterReceiptSeqCode')"
              
              v-model.trim="modelForm.receiptSeqCode"
              :maxlength="50"
              :disabled="receiptSeqId != ''"
            ></Input>
          </Form-item>
        </Col>
        <Col span="12" style="border:none;">
          <Form-item prop="receiptSeqName" :label="$t('module.receiptSequence.receiptSeqName')">
            <Input
              :placeholder="$t('module.receiptSequence.enterReceiptSeqName')"
              
              v-model="modelForm.receiptSeqName"
              :maxlength="50"
            ></Input>
          </Form-item>
        </Col>
      </Row>
      <Row :gutter="32" class="code-row-bg">
        <Col span="12" style="border:none;">
          <Form-item prop="resetFrequency" :label="$t('module.receiptSequence.resetFrequency')">
            <Select  v-model="modelForm.resetFrequency">
              <Option
                :title="$t('module.receiptSequence.resetFrequencyOption.everyDay')"
                value="DAILY"
                key="DAILY"
              >{{$t('module.receiptSequence.resetFrequencyOption.everyDay')}}</Option>
              <Option
                :title="$t('module.receiptSequence.resetFrequencyOption.everyMonth')"
                value="MONTHLY"
                key="MONTHLY"
              >{{$t('module.receiptSequence.resetFrequencyOption.everyMonth')}}</Option>
              <Option
                :title="$t('module.receiptSequence.resetFrequencyOption.everyYear')"
                value="YEARLY"
                key="YEARLY"
              >{{$t('module.receiptSequence.resetFrequencyOption.everyYear')}}</Option>
              <Option
                :title="$t('module.receiptSequence.resetFrequencyOption.never')"
                value="NEVER"
                key="NEVER"
              >{{$t('module.receiptSequence.resetFrequencyOption.never')}}</Option>
            </Select>
          </Form-item>
        </Col>
        <Col span="12" style="border:none;">
          <Form-item prop="isAvailable" :label="$t('common.status')">
            <RadioGroup v-model="modelForm.isAvailable">
              <Radio :label="1">{{$t('common.enable')}}</Radio>
              <Radio :label="0">{{$t('common.disable')}}</Radio>
            </RadioGroup>
          </Form-item>
        </Col>
      </Row>
      <!-- module.receiptSequence.receiptSeqDesc 单据序列描述 改为 描述 -->
      <Form-item :label="$t('common.describe')">
        <Input
          type="textarea"
          :rows="4"
          placeholder
          
          v-model="modelForm.receiptSeqDesc"
          :maxlength="100"
        ></Input>
      </Form-item>
    </Form>
  </div>
</template>
<script>
import { GetValueSetByCode } from "./common.js";
import valueSet from "@lang/modules/valueSet";
import receiptSequence from "@lang/modules/receiptSequence";
import tenantAPI from "@api/tenantApi.js";
import { CoreModuleName } from "@/const.js";
import { codeReg } from "@/const.js";

export default {
  // components:{},
  locales: {
    "zh-CN": {
      module: {
        receiptSequence: receiptSequence["zh-CN"],
        valueSet: valueSet["zh-CN"]
      }
    },
    "en-US": {
      module: {
        receiptSequence: receiptSequence["en-US"],
        valueSet: valueSet["en-US"]
      }
    }
  },
  props: {
    adminProductId: {
      type: String,
      default() {
        return "";
      }
    },
    tenantCode: {
      type: String,
      default() {
        return "";
      }
    },
    receiptSeqId: {
      type: String,
      default() {
        return "";
      }
    },
    version: {
      type: String,
      default() {
        return "";
      }
    }
  },
  data() {
    const validateReceiptSeqCode = (rule, value, callback) => {
      if (value === "") {
        callback(new Error(this.$t("module.receiptSequence.enterReceiptSeqCode")));
      } else if (value.length > 30) {
        callback(new Error(this.$t("common.warning.codeCheckLength")));
      } else if (!new RegExp(codeReg).test(value)) {
        callback(new Error(this.$t("common.warning.codeCheckCharacter")));
      } else if (new RegExp("[\u4e00-\u9fa5]").test(value)) {
        callback(new Error(this.$t("common.warning.codeCheckCharacter")));
      }
      callback();
    };
    return {
      modelForm: {
        id: this.receiptSeqId,
        receiptSeqCode: "",
        receiptSeqName: "",
        resetFrequency: "DAILY",
        receiptSeqDesc: "",
        isAvailable: 1
      },
      productList: [],
      tenantList: [],
      currTenantCode: "",
      rule: {
        receiptSeqCode: [{ required: true, validator: validateReceiptSeqCode, trigger: "blur" }],
        receiptSeqName: [
          { required: true, message: this.$t("module.receiptSequence.enterReceiptSeqName"), trigger: "blur" }
        ]
      },
      actions: [
        {
          text: this.$t("common.save"),
          theme: "primary",
          handle: () => {
            this.save();
          },
          loading: false
        },
        {
          text: this.$t("common.close"),
          handle: () => {
            this.$emit("Close");
          }
        }
      ]
    };
  },
  computed: {},
  created: function() {
    if (this.receiptSeqId) {
      this.$emit("SetTitle", this.$t("module.receiptSequence.editReceiptSequence"));
    } else {
      this.initProduct();
      this.$emit("SetTitle", this.$t("module.receiptSequence.createReceiptSequence"));
    }

    this.$emit("SetPageWidth", 700);
    this.$emit("SetPageActions", this.actions);

    const { userInfo } = $store.state[CoreModuleName];
    this.currTenantCode = userInfo.tenantCode;
  },
  beforeMount: function() {},
  mounted: function() {
    this.init();
  },
  beforeDestroy: function() {},
  destroyed: function() {},
  methods: {
    initProduct() {
      GetValueSetByCode({ code: "RC_PRODUCT" }).then(data => {
        this.productList = data;
      });

      if (!this.receiptSeqId) {
        this.modelForm.productId = this.adminProductId;
      }
    },
    init() {
      if (this.receiptSeqId) {
        $http
          .post(`${window.RPConfig.setting}/sys/receiptSeq/detail?id=${this.receiptSeqId}`)
          .then(response => response.data)
          .then(response => {
            this.modelForm = {
              id: response.id,
              receiptSeqCode: response.receiptSeqCode,
              receiptSeqName: response.receiptSeqName,
              resetFrequency: response.resetFrequency,
              receiptSeqDesc: response.receiptSeqDesc,
              isAvailable: parseInt(response.isAvailable),
              productId: response.productId,
              version: this.version,
              tenantCode: this.currTenantCode
            };

            this.initProduct();
          });
      }
      this.initTenant();
    },
    // 初始化所属租户
    initTenant() {
      if (this.receiptSeqId) {
        tenantAPI.queryAllTenantList().then(data => {
          this.tenantList = data;
        });
      } else {
        tenantAPI.queryTenantList().then(data => {
          this.tenantList = data;
        });
      }
      // 新增时
      if (this.receiptSeqId == "" && this.currTenantCode) {
        this.modelForm.tenantCode = this.currTenantCode;
      }
    },
    save() {
      this.$refs["editForm"].validate(valid => {
        if (valid) {
          this.actions[0].loading = true;
          if (this.receiptSeqId) {
            $http
              .post(`${window.RPConfig.setting}/sys/receiptSeq/update`, this.modelForm)
              .then(response => response.data)
              .then(response => {
                this.actions[0].loading = false;
                this.$message.success({
                  content: this.$t("module.receiptSequence.updateSuccess"),
                  duration: 3
                });
                this.$emit("Close", true);
              })
              .catch(err => {
                this.actions[0].loading = false;
              });
          } else {
            $http
              .post(`${window.RPConfig.setting}/sys/receiptSeq/save`, this.modelForm)
              .then(response => response.data)
              .then(response => {
                this.actions[0].loading = false;
                this.$message.success({
                  content: this.$t("module.receiptSequence.createSuccess"),
                  duration: 3
                });
                this.$emit("Close", true);
              })
              .catch(err => {
                this.actions[0].loading = false;
              });
          }
        } else {
          this.$message.error({
            content: this.$t("common.formValidateFailed"),
            duration: 3
          });
          return 0;
        }
      });
    }
  },
  watch: {},
  directives: {}
};
</script>